package com.dodoke.service.impl;

import com.dodoke.dao.RoleDao;
import com.dodoke.dao.UserDao;
import com.dodoke.entity.Role;
import com.dodoke.entity.User;
import com.dodoke.service.UserService;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    private RoleDao roleDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    /**
     * 获取所有用户的列表
     * @return
     */
    @Override
    public List<User> getAllList() {
        List<User> userList = userDao.findAllList();
        // 遍历每一个用户对象进行所属觉得查询
        for (User user: userList) {
           // 根据用户id进行所属角色查询
            List<Role> roleList = roleDao.getRoleListByUserId(user.getId());
            user.setRoleList(roleList);
        }
        return userList;
    }

    /**
     * 保存用户
     * @param user
     */
    @Override
    public void save(User user,Integer[] roleIds) {
        Integer userId = userDao.addUser(user);
        // 根据用户ID和角色ID 保存到数据的sys_user_role表
        for(Integer roleId: roleIds){
            userDao.addUserRole(userId, roleId);
        }
    }

    /**
     * 删除用户信息
     * @param userId
     */
    @Override
    public void delUser(Integer userId) {
        // 1.删除用户的关联关系
        userDao.deleteRoleByUserId(userId);
        // 2.删除用户信息
        userDao.deleteByUserId(userId);
    }

    /**
     * 用户登录实现
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        try {
            User user = userDao.findInfoByUsernameAndPassword(username,password);
            return user;
        }catch (EmptyResultDataAccessException ex){
            System.err.println(ex.getMessage());
            return null;
        }
    }
}
